<template>
  <div v-if="isShowSkeleton" class="mt20">
    <van-skeleton title :row="5" />
  </div>
  <div v-else class="pageBox">
    <div class="add" @click="showPopup = true">
      <van-icon name="add-o" size="20" color="#40a9ff" />
    </div>

    <div class="comment-wrapper" ref="commentScrollWrap">
      <van-empty description="暂无数据" v-if="!total" />

      <div class="comment">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list v-if="total > 0" v-model:loading="loading" :finished="finished" finished-text="没有更多了"
            v-model:error="error" error-text="请求失败，点击重新加载" @load="onLoad" :offset="50">
            <div v-for="item in list" :key="item.id" class="commentItem">
              <div class="flexBox aiCenter flexBetween">
                <div class="flexBox aiCenter">
                  <img v-if="item.user.avatar" :src="handleImgSrc(item.user.avatar)" alt="" class="avatar mr15">
                  <div class="fs24 c-333">{{ item.user.nickname }}</div>
                </div>
                <div class="fs24 c-999">{{ changeTime(item.create_time, 'YYYY-MM-DD') }}</div>
              </div>
              <div class="fs26 mt10 twoLine breakAll">{{ item.name }}</div>
            </div>
          </van-list>
        </van-pull-refresh>
      </div>
    </div>

    <van-popup v-model:show="showPopup" position="bottom" :style="{ height: '30%' }" closeable
      :close-on-click-overlay="false" @click-close-icon="closePopup">
      <div class="mt100">
        <van-cell-group inset>
          <van-field v-model="nameVal" label="名称" placeholder="请输入名称" />
        </van-cell-group>
        <div class="mt30 ml30 mr30">
          <van-button type="primary" block @click="submit">添加</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, reactive, ref } from 'vue'
import { commentList, commentSave } from '@/api/user'
import { showToast } from 'vant'
import { changeTime, handleImgSrc } from '@/utils'
import { useRoute } from 'vue-router'
import { CommentListType, CommonPage } from '@/types/userTypes'

const list = ref<CommentListType[]>([])
const total = ref(0)
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(true)
const error = ref(false)
const showPopup = ref(false)
const nameVal = ref('')
const isShowSkeleton = ref(true)
const commentScrollWrap = ref<HTMLDivElement | null>(null)
const pageData = reactive({
  page: 1,
  pageSize: 10
})
const route = useRoute()

const getCommentList = async () => {
  if (list.value.length >= total.value && list.value.length > 0) {
    loading.value = false
    finished.value = true
    return
  }
  try {
    const params = { ...pageData } as { user_id: number } & CommonPage
    if (route.query.userId) {
      params.user_id = Number(route.query.userId)
    }
    const { data } = await commentList(params)
    if (data.code === 0) {
      isShowSkeleton.value = false
      list.value = [...list.value, ...data.data.entries]
      total.value = data.data.total
      finished.value = list.value.length === total.value
    }
  } catch (err) {
    error.value = true
  }
  loading.value = false
}

const onLoad = () => {
  setTimeout(() => {
    pageData.page++
    getCommentList()
  }, 500)
}

const onRefresh = () => {
  list.value = []
  pageData.page = 1
  setTimeout(() => {
    getCommentList()
    refreshing.value = false
  }, 500)
}

const closePopup = () => {
  showPopup.value = false
  nameVal.value = ''
}

const submit = async () => {
  if (!nameVal.value) return showToast('请输入名称')
  if (nameVal.value.length < 5 || nameVal.value.length > 50) return showToast('名称长度为5-50个字符')

  const { data } = await commentSave({ name: nameVal.value })
  if (data.code === 0) {
    showToast('已添加')
    list.value = []
    total.value = 0
    pageData.page = 1
    nameVal.value = ''
    showPopup.value = false
    getCommentList()
  } else {
    showToast(data.msg)
  }
}

// 滚动时显示滚动条
const handleScroll = () => {
  if (commentScrollWrap.value) {
    // 现代浏览器：修改滚动条颜色
    commentScrollWrap.value.style.scrollbarColor = 'rgba(191, 191, 191, 0.8) rgba(191, 191, 191, 0.2)'

    // 清除自动隐藏的定时器
    if (window.scrollBarTimer) {
      clearTimeout(window.scrollBarTimer)
    }

    // 滚动停止后，延迟隐藏滚动条
    window.scrollBarTimer = setTimeout(() => {
      commentScrollWrap.value!.style.scrollbarColor = 'rgba(0, 0, 0, 0) rgba(0, 0, 0, 0.1)'
    }, 500)
  }
}

onMounted(async () => {
  await getCommentList()
  if (commentScrollWrap.value) {
    commentScrollWrap.value.addEventListener('scroll', handleScroll)
  }
})

onUnmounted(() => {
  if (commentScrollWrap.value) {
    commentScrollWrap.value.removeEventListener('scroll', handleScroll)
    clearTimeout(window.scrollBarTimer)
  }
})
</script>

<style lang="scss" scoped>
.van-popup {
  background: #F7F8FA;
}

.pageBox {
  background: #ffffff;
  padding-top: 10px;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;

  .add {
    position: absolute;
    top: -65px;
    right: 35px;
    z-index: 999;
  }

  .comment-wrapper {
    flex: 1;
    overflow-y: auto;
    scrollbar-width: thin;
    padding: 0 20px;
    scrollbar-color: rgba(0, 0, 0, 0) rgba(0, 0, 0, 0.1);
    transition: scrollbar-color 0.3s ease;

    // WebKit 内核浏览器
    &::-webkit-scrollbar {
      width: 4px;
    }

    &::-webkit-scrollbar-track {
      background: rgba(0, 0, 0, 0.1);
      // 轨道浅灰色
    }

    &::-webkit-scrollbar-thumb {
      background-color: rgba(0, 0, 0, 0);
      // 初始透明
      border-radius: 2px;
      transition: background-color 0.3s ease;
    }

    &:hover::-webkit-scrollbar-thumb,
    &:scrollbarthumbvertical::-webkit-scrollbar-thumb {
      background-color: rgba(0, 0, 0, 0.4);
    }

    .comment {
      width: 100%;

      .commentItem {
        margin-bottom: 5px;
        padding: 15px 0;
        border-bottom: 1px solid #F2F2F2;

        .avatar {
          width: 50px;
          height: 50px;
          border-radius: 50%;
        }
      }
    }
  }
}
</style>